package com.lengmou.ctrl;

import com.alibaba.fastjson.JSONObject;
import com.lengmou.entity.*;
import com.lengmou.service.*;
import com.lengmou.util.TimeTool;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import javax.annotation.Resource;
import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.util.ArrayList;
import java.util.List;

@Controller
@RequestMapping("/user")
public class UsersController {
    @Resource
    private UsersService usersService;

    @Resource
    private CarsService carsService;
    @Resource
    private GoodsService goodsService;
    @Resource
    private OrdersService ordersService;
    @Resource
    private OrdersInfoService ordersInfoService;
    @Resource
    private CouponsService couponsService;

    @RequestMapping(value = "/login",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String login(Users users, HttpSession session, boolean remember, HttpServletResponse resp){
        JSONObject json = new JSONObject();
        Users login = usersService.login(users);
        if(login!=null){
            session.setAttribute("user",login);
            json.put("success",1);
            if(remember){
                Cookie cookie = new Cookie("username",users.getUsername());
//                保存7天
                cookie.setMaxAge(60*60*24*7);
                resp.addCookie(cookie);
            }
        }else{
            json.put("success",0);
        }
        return json.toJSONString();
    }

    @RequestMapping(value = "/reg",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String reg(Users users,HttpSession session){
        JSONObject json = new JSONObject();
        int reg = usersService.reg(users);
        System.out.println(reg);
        if(reg==-1){
            json.put("success",-1);
        }else if(reg==1){
//            判断如果返回的是用户id那么就返回注册成功信息
            json.put("success",1);
//            获取刚刚注册成功的用户对象
            Users userByName = usersService.getUserByName(users.getUsername());
//            会话加入用户对象
            session.setAttribute("user",userByName);
        }
        return json.toString();
    }

//    判断是否存在该账户
    @RequestMapping(value = "/existsUsername",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String existsUsername(String username){
        JSONObject json = new JSONObject();
        Users userByName = usersService.getUserByName(username);
        if(userByName==null){
            json.put("success",1);
        }else{
            json.put("success",0);
        }
        return json.toString();
    }
//    判断是否存在该手机号码
    @RequestMapping(value = "/existsUserTel",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String existsUserTel(String tel){
        JSONObject json = new JSONObject();
        Users user = usersService.getUsersByTel(tel);
        if(user==null){
            json.put("success",1);
        }else{
            json.put("success",0);
        }
        return json.toString();
    }

//    将商品加入购物车
    @RequestMapping(value = "/addCars",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String addGoodsCars(int goodsid,int num,HttpSession session){
        JSONObject json = new JSONObject();
        Users user = (Users) session.getAttribute("user");
        if(user!=null){
            int id = user.getId();
            int i = carsService.addCars(new Cars("", goodsid, id, num, null));
            json.put("state",i);
        }else{
            json.put("state",-1);
        }
        return json.toString();
    }

    @RequestMapping("/cars")
    public ModelAndView userCars(HttpSession session){
        ModelAndView mav = new ModelAndView();
        Users user =(Users) session.getAttribute("user");
        if (user!=null){
            mav.setViewName("cars");
            List<Cars> carsByUserId = carsService.getCarsByUserId(user.getId());
            mav.addObject("cars",carsByUserId);
        }else{
            mav.setViewName("forward:/login.jsp");
        }
        return mav;
    }
//    修改购物车商品数量
    @RequestMapping(value = "/setCarsNum",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String setCarsNum(String carid,int num,HttpSession session){
        Users user =(Users) session.getAttribute("user");
        JSONObject json = new JSONObject();
        if(user!=null){
            Cars byId = carsService.getById(carid);
            if(byId!=null){
                if(byId.getUserid()==user.getId()){
                    if(num>0){
                        byId.setNum(num);
                        int i = carsService.setCarsNum(byId);
                        json.put("state",i);
                    }else{
                        json.put("state",-4);
                    }
                }else{
                    json.put("state",-2);
                }
            }else{
                json.put("state",-3);
            }
        }else{
            json.put("state",-1);
        }
        return json.toString();
    }
//    删除购物车
    @RequestMapping(value = "/deleteCars",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String deleteCars(String carid,HttpSession session){
        Users user =(Users) session.getAttribute("user");
        JSONObject json = new JSONObject();
        if(user!=null){
            Cars byId = carsService.getById(carid);
            if(byId!=null&&byId.getUserid()==user.getId()){
                int i = carsService.deleteCars(byId.getId());
                json.put("state",i);
            }else{
                json.put("state",-2);
            }
        }else{
            json.put("state",-1);
        }
        return json.toString();
    }

//    添加到结算区域
    @RequestMapping(value = "/addConfirm",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String addConfirm(@RequestParam("carsids[]") List<String> carsids,HttpSession session){
        JSONObject json = new JSONObject();
        List<Cars> carsList = new ArrayList<>();
        Users user = (Users)session.getAttribute("user");
        if(user!=null){
            for (String carsid:carsids) {
                Cars byId = carsService.getById(carsid);
                if(byId!=null&&byId.getUserid()==user.getId()){
                    carsList.add(byId);
                }else{
                    json.put("state",-3);//参数错误
                    return json.toString();
                }
            }
            json.put("state",1);
            session.setAttribute("confrim",carsList);
        }else{
            json.put("state",-1);//没登录
        }
        return json.toString();
    }


//    购物车里的结算
    @RequestMapping("/confirmByCar")
    public ModelAndView confirmByCar(HttpSession httpSession){
        ModelAndView mav = new ModelAndView();
        List<Cars> confrim =(List<Cars>) httpSession.getAttribute("confrim");
        if(confrim!=null){
            mav.addObject("cars",confrim);
            mav.setViewName("confirm");
        }else{
            mav.setViewName("list");
        }
        return mav;
    }
//    添加订单
    @RequestMapping(value = "/buy",produces = "application/json; charset=utf-8")
    @ResponseBody
    public String buy(String couponsid,HttpSession session,String remarks){
        JSONObject json = new JSONObject();
        Users user =(Users) session.getAttribute("user");
        List<Cars> confirm = (List<Cars>)session.getAttribute("confrim");
        if(confirm!=null&&confirm.size()>0){
            Orders orders = new Orders(0, user.getId(), null, null, remarks, 0);
            int i = ordersService.addOrders(orders);
            if(i==1){
//                判断该优惠券是否满足条件
                if(couponsService.existsUse(countPrice(confirm),couponsid)){
                    couponsService.useCoupons(couponsid,orders.getId());
                }
                int state=0;
                for (Cars car:confirm) {
                    state+=ordersInfoService.addOrdersInfo(new OrdersInfo(null,orders.getId(),car.getGoodsid(),car.getNum()));
                }
                if(state==confirm.size()){
                    json.put("state",1);
                    json.put("ordersid",orders.getId());
                }else{
//                    添加详情订单失败
                    json.put("state",-3);
                }
            }else{
//                添加主订单失败
                json.put("state",-1);
            }
        }else{
//            当前没有需要准备结算商品
            json.put("state",-2);
        }
        return json.toString();
    }

//    结算订单
@RequestMapping(value = "/pay",produces = "application/json; charset=utf-8")
@ResponseBody
    public String pay(int orderid,HttpSession session){
        JSONObject json = new JSONObject();
        Users user = (Users)session.getAttribute("user");
        Orders ordersById = ordersService.getOrdersById(orderid);
        List<OrdersInfo> infoByOrdersId = ordersInfoService.getInfoByOrdersId(orderid);
        if(user!=null){
            Users userById = usersService.getUserById(user.getId());
            if(ordersById!=null&&ordersById.getUserid()==user.getId()&&ordersById.getState()==0){
                double price = countOrderInfoPrice(infoByOrdersId);
                Coupons couponsByOrdersId = couponsService.getCouponsByOrdersId(orderid);
                if(couponsByOrdersId!=null){
                    price-=couponsByOrdersId.getCut();
                }
                if(userById.getMoney()>price){
                    int i = usersService.subUsersMoney(userById.getId(), price);
                    ordersById.setState(1);
                    ordersById.setPaytime(TimeTool.time());
                    int i1 = ordersService.setOrdersState(ordersById);
                    if(i>0&&i1>0){
                        //                    支付成功
                        json.put("state",1);
                    }else{
//                        支付失败
                        json.put("state",-3);
                    }
                }else{
//                    支付失败余额不足
                    json.put("state",2);
                }
            }else{
//            没有该订单
                json.put("state",-1);
            }
        }else{
//            根本没登录
            json.put("state",-2);
        }

        return json.toString();
    }

//  取消订单
@RequestMapping(value = "/cancelOrders",produces = "application/json; charset=utf-8")
@ResponseBody
    public String cancelOrders(int orderid,HttpSession session){
        JSONObject json = new JSONObject();
        Users user = (Users) session.getAttribute("user");
        if(user!=null){
            Orders ordersById = ordersService.getOrdersById(orderid);
            if(ordersById!=null&&ordersById.getUserid()==user.getId()&&ordersById.getState()==0){
                ordersById.setState(-1);
                int i = ordersService.setOrdersState(ordersById);
                if(i>0){
//                    修改成功
                    json.put("state",1);
                }else{
//                    修改订单状态失败了
                    json.put("state",-3);
                }
            }else{
//                不存在该订单
                json.put("state",-2);
            }
        }else{
//            没有登录
            json.put("state",-1);
        }
        return json.toString();
    }



//    订单详情页

    @RequestMapping("/test")
    public void test(){
        Orders orders = new Orders(1, 1, "12", null, null, 11);

        int i = ordersService.addOrders(orders);
        System.out.println("订单id："+orders.getId());
    }

//    计算购物车内的商品价格
    public double countPrice(List<Cars> cars){
        double price = 0;
        for (Cars car:cars) {
            Goods goodsById = goodsService.getGoodsById(car.getGoodsid());
            if(goodsById!=null){
                price+=goodsById.getPrice()*car.getNum();
            }
        }
        return price;
    }
//    计算订单详情的价格
    public double countOrderInfoPrice(List<OrdersInfo> ordersInfos){
        double price = 0;
        for (OrdersInfo info:ordersInfos) {
            Goods goodsById = goodsService.getGoodsById(info.getGoodsid());
            if(goodsById!=null){
                price+=goodsById.getPrice()*info.getNum();
            }
        }
        return price;
    }


}
